import asyncio
import threading
from flask import Flask, request

app = Flask(__name__)

# 共享变量
x = 0

# 副线程：循环检查 x 的值
async def check_x():
    global x
    while True:
        if x == 1:
            print("ok")
            x = 0  # 重置 x
        print(f"x = {x}")  # 打印当前 x 的值
        await asyncio.sleep(0.5)  # 避免忙等待

# Flask 路由：接收请求修改 x 的值
@app.route("/set_x", methods=["POST"])
def set_x():
    global x
    data = request.json
    if "x" in data:
        x = data["x"]
        return f"x updated to {x}\n"
    return "Invalid request\n", 400

# 启动 Flask 服务器
def run_flask():
    app.run(port=5000)

# 主函数
async def main():
    # 启动 Flask 服务器在一个单独的线程中
    flask_thread = threading.Thread(target=run_flask, daemon=True)
    flask_thread.start()

    # 启动检查 x 的任务
    await check_x()

# 运行事件循环
asyncio.run(main())